import { init } from "./loadConfig.js";
init();
import { translate } from "./getTranslate.js";
import { findText } from "./find.js";
import "./toExcel.js";
async function handelSearch(e) {
  const keyword = $("#keyword").val();
  // 打开中文目录
  let one = null;
  window.$config.lang.map((item) => {
    console.log("readTranslateOne", item);
    if (item.code == "zh-cn") {
      one = item;
    }
  });
  let arr = one.file.split(".");
  const fileType = arr[arr.length - 1];
  if (!one) {
    // 写入错误
    $("#errmsg").text("没找到中文文件");
  }
  if (fileType === "json") {
    const res = window.$readFile(one.file);
    const obj = JSON.parse(res);
    findText(keyword, obj);
  } else if (fileType === "js") {
    const obj = await import(one.file);
    console.log(obj);
    findText(keyword, obj.default);
  } else if (fileType === "ts") {
    let res = window.$readFile(one.file);
    let tempFile = window.$createTempFile(res);
    console.log("tempFile", tempFile);
    // 转js
    const obj = await import(tempFile);
    window.$deleteFile(tempFile);
    console.log(obj);
    findText(keyword, obj.default);
  } else {
    alert("仅支持JSON,js,ts文件");
  }
}
let isOpenConfig = false;
$("#config").hide();
function setSelectIndex(index) {
  utools.db.remove("configSelectIndex");
  utools.db.put({
    _id: "configSelectIndex",
    data: index,
  });
}
function getSelectIndex() {
  return utools.db.get("configSelectIndex")?.data || 0;
}
function handleSaveConfig() {
  isOpenConfig = !isOpenConfig;
  if (isOpenConfig) {
    // 编辑
    $("#config").show();
    $("#setConfig").text("保存");
    $("#configArea").val(JSON.stringify(window.$config));
    $("#saveName").val(window.$config.name ? window.$config.name : "");
  } else {
    // 保存
    let name = $("#saveName").val();
    console.log("保存预设名称", name);
    $("#config").hide();
    $("#setConfig").text("编辑参数");
    const configStr = $("#configArea").val();
    console.log("configStr", configStr);
    try {
      const config = JSON.parse(configStr);
      config.name = name;
      console.log("config", config, typeof config !== "object");
      if (typeof config !== "object") {
        throw "error";
      }
      const list = getConfigList();
      const index = getSelectIndex();
      console.log("保存的index", index);
      list.splice(index, 1, config);
      saveList(list);
      window.$config = config;
      utools.db.remove("config");
      utools.db.put({
        _id: "config",
        data: window.$config,
      });
      init();
      return true;
    } catch (e) {
      $("#errmsg").text("参数配置错误！！！");
      return false;
    }
  }
  initSaveList();
}
$("#setConfig").on("click", () => {
  handleSaveConfig();
});

function getConfigList() {
  let list = utools.db.get("configList");
  console.log("list", list);
  if (list && list.data) {
    list = JSON.parse(list.data);
  } else {
    list = [];
  }
  if (Array.isArray(list)) {
    return list;
  } else {
    return [];
  }
}

function initSaveList() {
  $("#configSaveList .btnList").html("");
  const list = getConfigList();
  console.log("initSaveList list", list);
  if (Array.isArray(list)) {
    list.forEach((item, index) => {
      try {
        console.log("item", item);
        let obj = item;
        if (typeof item == "object") {
        } else {
          obj = JSON.parse(item);
        }
        list[index] = JSON.stringify(obj);
        console.log("obj.name", obj.name);
        if (getSelectIndex() == index) {
          $("#saveName").val(obj.name);
        }
        const btn = $(
          `<button id="${"configSave_btn_" + index} index="${index}">${
            obj.name
          }</button>`
        );
        const del = $(
          `<button id="${
            "configSave_btn_del_" + index
          } index="${index}">删除</button>`
        );
        $("#configSaveList .btnList").append(btn);
        $("#configSaveList .btnList").append(del);
        btn.on("click", () => {
          console.log("点击了", index);
          $("#configArea").val(list[index]);
          setSelectIndex(index);
          // handleSaveConfig();
          initSaveList();
        });
        del.on("click", () => {
          console.log("删除了", index);
          list.splice(index, 1);
          saveList(list);
          console.log("delList", getConfigList());
          initSaveList();
        });
      } catch (e) {
        console.log("err", e);
        list.splice(index, 1);
      }
    });
  }
}
function saveList(list) {
  utools.db.remove("configList");
  utools.db.put({
    _id: "configList",
    data: JSON.stringify(list),
  });
}
initSaveList();
$("#configSaveNew").on("click", function () {
  console.log("保存为预设");
  // 读取预设
  const configStr = $("#configArea").val();
  console.log("configStr", configStr);
  if (handleSaveConfig()) {
    utools.showNotification("保存成功!");
    const list = getConfigList();
    list.push(configStr);
    utools.db.remove("configList");
    utools.db.put({
      _id: "configList",
      data: JSON.stringify(list),
    });
  } else {
    utools.showNotification("保存失败!");
  }
});

$("#find").on("click", handelSearch);
$("body").on("keydown", (e) => {
  if (e.originalEvent.code === "Enter") {
    handelSearch();
  }
});
document.addEventListener("visibilitychange", function () {
  if (document.visibilityState === "visible") {
    console.log("窗口已切换到当前窗口");
    // 在这里添加您的逻辑
    $("#keyword").focus();
  }
});
console.log("window", window);
$(".token a").on("click", () => {
  utools.ubrowser
    .goto("http://translate.codeai.net.cn/")
    .run({ width: 1000, height: 600 });
});
utools.onPluginEnter(({ code, type, payload, option }) => {
  const features = utools.getFeatures();
  console.log("features", features);
  console.log("clip.readText()", window.$clip.readText());
  console.log("用户进入插件应用", code, type, payload);
  // payload 获取到的输入值
  window.$i = {};
  window.$i.payload = window.$clip.readText() || payload;
  let k = utools.db.get("objKey");
  if (k) {
    console.log("k!!!!", k);
    $("#objKey").val(k.data);
    $("#i18n").text(`$t('${k.data}')`);
  }

  let t = utools.db.get("token");
  if (t) {
    $("#token").val(t.data);
  }
  // 渲染
  console.log("$('.input')", $(".input"));
  $("#keyword").val(window.$i.payload);
});
async function toTranslateOne(code) {
  $(`#${code}`).removeClass("success");
  if (!code) return Promise.reject("语言码错误");
  if (!window.$i.data) {
    window.$i.data = {};
  }
  const tText = await translate(window.$i.payload, code);
  if (!tText) {
    return Promise.reject("翻译接口错误");
  }
  console.log("tText", tText);
  window.$i.data[code] = tText;
  $(`#${code} .data`).html(tText);
  $(`#rewrite-${code}`).val(tText);
  $(`#${code}`).addClass("success");
}

function addKey(key, value, obj, cover = false, spl = true) {
  if (spl) {
    let keys = key.split(".");
    if (!obj) {
      obj = {};
    }
    if (keys[0]) {
      if (typeof obj[keys[0]] == "object") {
        // 存在对象
        if (keys.length > 1) {
          console.log("递归！", keys.slice(1).join("."), value, obj[keys[0]]);
          addKey(keys.slice(1).join("."), value, obj[keys[0]], cover, spl);
        } else {
          // 出现问题原来是个对象现在要直接覆盖成值？
          console.log("// 出现问题原来是个对象现在要直接覆盖成值？");
          if (!cover && obj[keys[0]]) {
            // alert('属性已存在')
            throw "属性已存在";
          }
          obj[keys[0]] = value;
        }
      } else {
        if (keys.length > 1) {
          obj[keys[0]] = {};
          addKey(keys.slice(1).join("."), value, obj[keys[0]], cover, spl);
        } else {
          // 直接覆盖
          console.log("直接覆盖", keys[0], obj);
          if (!cover && obj[keys[0]]) {
            // alert('属性已存在')
            throw "属性已存在";
          }
          obj[keys[0]] = value;
        }
      }
    }
  } else {
    obj[key] = value;
  }
  return obj;
}
window.$addKey = addKey;
function checkKey(key, obj, spl = true) {
  if (spl) {
    let keys = key.split(".");
    if (!obj) {
      obj = {};
    }
    if (keys[0]) {
      if (typeof obj[keys[0]] == "object") {
        // 存在对象
        if (keys.length > 1) {
          console.log("递归！", keys.slice(1).join("."), obj[keys[0]]);
          checkKey(keys.slice(1).join("."), obj[keys[0]], true);
        } else {
          // 出现问题原来是个对象现在要直接覆盖成值？
          console.log("// 出现问题原来是个对象现在要直接覆盖成值？");
          if (obj[keys[0]]) {
            // alert('属性已存在')
            throw "属性已存在";
          }
        }
      } else {
        if (keys.length > 1) {
          obj[keys[0]] = {};
          checkKey(keys.slice(1).join("."), obj[keys[0]], true);
        } else {
          // 直接覆盖
          console.log("直接覆盖", keys[0], obj);
          if (obj[keys[0]]) {
            // alert('属性已存在')
            throw "属性已存在";
          }
        }
      }
    }
  } else {
    obj[key] = value;
  }
  return obj;
}
async function sleep(seconds) {
  return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}
window.$sleep = sleep;
$("#reset").on("click", async () => {
  utools.db.remove("objKey");
  utools.db.remove("token");
  utools.db.remove("config");
  window.$initConfig();
  init();
});
$("#i18nBtn").on("click", async () => {
  let key = $("#objKey").val();
  $("#state").text("复制成功");
  utools.copyText(`$t('${key}')`);
});
$("#i18nBtn2").on("click", async () => {
  let key = $("#objKey").val();
  $("#state").text("复制成功");
  key = key.replace("common.", "");
  utools.copyText(`$t('${key}')`);
});
$("#objKey").on("input", (e) => {
  console.log("el", $("#objKey").val());
  $("#objKey").val();
  $("#i18n").text(`$t('${$("#objKey").val()}')`);
  utools.copyText(`$t('${$("#objKey").val()}')`);
});
async function handleConfirm(cover = false) {
  $("#state").text("翻译中");
  $("#errmsg").text("");
  console.log("cover", cover);
  let key = $("#objKey").val();
  // 加入剪贴板
  utools.copyText(`$t('${key}')`);
  $("#i18n").text(`$t('${key}')`);
  if (!key) {
    alert("请先输入键值");
    return;
  }
  utools.db.remove("objKey");
  utools.db.put({
    _id: "objKey",
    data: key,
  });
  const token = $("#token").val();
  utools.db.remove("token");
  utools.db.put({
    _id: "token",
    data: token,
  });
  window.$i.payload = $("#keyword").val();
  console.log("confirm", key);
  let err = "";
  window.$config.lang.map((item) => {
    $(`#${item.code}`).removeClass("success");
  });
  for (let i = 0; i < window.$config.lang.length; i++) {
    let item = window.$config.lang[i];
    try {
      console.log("item", item);
      if (!cover) {
        await checkOne(item.code, key);
      }
      await sleep(0.3);
      await toTranslateOne(item.code);
      await readTranslateOne(item.code, key, window.$i.data[item.code], cover);
    } catch (e) {
      console.log("err", e);
      err += `翻译${item.code}:错误,`;
      if (e) {
        if (typeof e === "string") {
          err += e;
        } else if (e.message) {
          err += e.message;
        }
      }
      err += ";\n";
      $("#errmsg").text(err);
    }
  }
  if (err) {
    $("#state").text("翻译完成，出错了");
    utools.showNotification("翻译出现错误!" + err);
  } else {
    $("#state").text("翻译完成");
    utools.showNotification("翻译完成!" + err);
  }
}
$("#confirm").on("click", () => {
  handleConfirm(false);
});
$("#confirmCover").on("click", () => {
  console.log("confirmCoverClick");
  handleConfirm(true);
});

function readTranslate(key, value) {
  window.$config.lang.map(async (item) => {
    let arr = item.file.split(".");
    const fileType = arr[arr.length - 1];
    if (fileType === "json") {
      const res = window.$readFile(item.file);
      const obj = JSON.parse(res);
      console.log("readFile", obj);
      const newObj = addKey(key, value, obj);
      window.$writeFile(item.file, JSON.stringify(newObj));
    } else if (fileType === "js") {
      const res = import(item.file);
      console.log(res);
    } else {
      alert("仅支持JSON文件");
    }
  });
}
window.$readTranslateOne = readTranslateOne;
async function readTranslateOne(code, key, value, cover = false) {
  let one = null;
  window.$config.lang.map((item) => {
    console.log("readTranslateOne", item);
    if (item.code == code) {
      one = item;
    }
  });
  let arr = one.file.split(".");
  const fileType = arr[arr.length - 1];
  // 备份一下
  if (!window.$back) {
    window.$back = {};
  }
  window.$back[code] = {
    file: one.file,
    content: window.$readFile(one.file),
  };
  if (fileType === "json") {
    const res = window.$readFile(one.file);
    const obj = JSON.parse(res);
    console.log("readFile", obj);
    const newObj = addKey(key, value, obj, cover);
    console.log("new Obj", newObj);
    await window.$writeFile(one.file, JSON.stringify(newObj, null, 2));
  } else if (fileType === "js") {
    if (!window.$checkFileExists(one.file)) {
      await window.$createFileIfNotExist(one.file);
      await window.$writeFile(one.file, "export default {}");
      await sleep(0.3);
    }
    const obj = await import(one.file);
    console.log(obj);
    const newObj = addKey(key, value, obj.default, cover);
    console.log("new Obj", newObj);
    await window.$writeFile(
      one.file,
      "export default " + JSON.stringify(newObj, null, 2)
    );
  } else if (fileType === "ts") {
    if (!window.$checkFileExists(one.file)) {
      await window.$createFileIfNotExist(one.file);
      await window.$writeFile(one.file, "export default {}");
      await sleep(0.3);
    }
    // const obj = await import(one.file);
    let res = window.$readFile(one.file);
    let tempFile = window.$createTempFile(res);
    console.log("tempFile", tempFile);
    // 转js
    const obj = await import(tempFile);
    console.log(obj);
    window.$deleteFile(tempFile);
    const newObj = addKey(key, value, obj.default, cover);
    console.log("new Obj", newObj);
    await window.$writeFile(
      one.file,
      "export default " + JSON.stringify(newObj, null, 2)
    );
  } else {
    alert("仅支持JSON,js,ts文件");
  }
}
$("#back").on("click", async () => {
  console.log("准备撤回");
  /*  window.$back[code] =  {
        file: one.file,
        content: window.$readFile(one.file)
    } */
  console.log("window.$back", window.$back);
  if (!window.$back) {
    $("#state").text("没有撤回内容");
    return;
  }
  $("#state").text("撤回中");
  for (const code in window.$back) {
    if (Object.hasOwnProperty.call(window.$back, code)) {
      const item = window.$back[code];
      console.log("item.content", item.content);
      if (!item.content) {
        item.content = "";
      }
      await window.$writeFile(item.file, item.content);
    }
  }
  $("#state").text("撤回完成");
});
async function checkOne(code, key) {
  let one = null;
  window.$config.lang.map((item) => {
    console.log("readTranslateOne", item);
    if (item.code == code) {
      one = item;
    }
  });
  let arr = one.file.split(".");
  const fileType = arr[arr.length - 1];
  if (fileType === "json") {
    const res = window.$readFile(one.file);
    const obj = JSON.parse(res);
    console.log("readFile", obj);
    checkKey(key, obj);
  } else if (fileType === "js") {
    if (!window.$checkFileExists(one.file)) {
      await window.$createFileIfNotExist(one.file);
      await window.$writeFile(one.file, "export default {}");
      await sleep(0.3);
    }
    const obj = await import(one.file);
    console.log(obj);
    checkKey(key, obj.default);
  } else if (fileType === "ts") {
    if (!window.$checkFileExists(one.file)) {
      await window.$createFileIfNotExist(one.file);
      await window.$writeFile(one.file, "export default {}");
      await sleep(0.3);
    }
    let res = window.$readFile(one.file);
    let tempFile = window.$createTempFile(res);
    console.log("tempFile", tempFile);
    // 转js
    const obj = await import(tempFile);
    window.$deleteFile(tempFile);
    console.log(obj);
    checkKey(key, obj.default);
  } else {
    alert("仅支持JSON,js,ts文件");
  }
}

async function handelSearchKey() {
  // 查找对应的中文
  const key = $("#objKey").val();
  console.log("key", key);
  // 打开中文目录
  let one = null;
  window.$config.lang.map((item) => {
    console.log("readTranslateOne", item);
    if (item.code == "zh-cn") {
      one = item;
    }
  });
  let arr = one.file.split(".");
  const fileType = arr[arr.length - 1];
  if (!one) {
    // 写入错误
    $("#errmsg").text("没找到中文文件");
  }
  if (fileType === "json") {
    const res = window.$readFile(one.file);
    const obj = JSON.parse(res);
    return findTextKey(key, obj);
  } else if (fileType === "js") {
    const obj = await import(one.file);
    console.log(obj);
    return findTextKey(key, obj.default);
  } else if (fileType === "ts") {
    let res = window.$readFile(one.file);
    let tempFile = window.$createTempFile(res);
    console.log("tempFile", tempFile);
    // 转js
    const obj = await import(tempFile);
    return findTextKey(key, obj.default);
  } else {
    alert("仅支持JSON,js文件");
  }
}

async function findTextKey(key, obj, spl = true) {
  let res = null;
  if (spl) {
    let keys = key.split(".");
    if (!obj) {
      obj = {};
    }
    if (keys[0]) {
      if (typeof obj[keys[0]] == "object") {
        // 存在对象
        if (keys.length > 1) {
          console.log("递归！", keys.slice(1).join("."), obj[keys[0]]);
          res = await findTextKey(keys.slice(1).join("."), obj[keys[0]], true);
        } else {
          // 出现问题原来是个对象现在要直接覆盖成值？
          console.log("// 出现问题原来是个对象现在要直接覆盖成值？");
          if (obj[keys[0]]) {
            // alert('属性已存在')
            res = obj[keys[0]];
          }
        }
      } else {
        if (keys.length > 1) {
          obj[keys[0]] = {};
          res = await findTextKey(keys.slice(1).join("."), obj[keys[0]], true);
        } else {
          // 直接覆盖
          console.log("直接覆盖", keys[0], obj);
          if (obj[keys[0]]) {
            // alert('属性已存在')
            res = obj[keys[0]];
            console.log("找到了", res);
          }
        }
      }
    }
  } else {
    return obj[key];
  }
  console.log("找到了!!!", res);
  if (res !== null) {
    $("#findResList").html("");
    const html = `<div class="row">
      <div class="value">${res}</div>
          <div class="key">${key}</div>
          <button id="copy-${key}">复制</button>
          <div class="tips success"></div>
      </div>`;
    $("#findResList").append(html);
  }
  return res;
}

$("#objKeyFind").on("click", async () => {
  console.log("objKeyFind", await handelSearchKey());
});
